package com.bdqn.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.pojo.Role;
import com.bdqn.pojo.User;
import com.bdqn.service.RoleService;
import com.bdqn.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户模块控制器
 *
 * @author
 * @since
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    /**
     * 查询用户列表分页显示
     */
    @RequestMapping("/list")
    public String list(Model model, String usrName, Long roleId, Long pageIndex) {
        // 如果为空,查第一页
        if (pageIndex == null) {
            pageIndex = 1L;
        }

        // 查询数据回显
        model.addAttribute("usrName", usrName);
        model.addAttribute("roleId", roleId);

        // 获取所有角色数据填充下拉框
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("roles", roles);

        // 使用页面传递的参数分页查询用户列表
        Page<User> page = new Page<>();
        page.setCurrent(pageIndex);
        IPage<User> userPager = userService.findUsers(usrName, roleId, page);
        model.addAttribute("userPager", userPager);

        return "user/list";
    }

    /**
     * 去到新增用户页面
     */
    @GetMapping("/add")
    public String toAdd(Model model) {
        // 获取所有角色数据填充下拉框
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("roles", roles);
        return "user/add";
    }

    /**
     * 去到修改用户页面
     */
    @GetMapping("/edit")
    public String toEdit(Model model, Long usrId) {
        // 获取所有角色数据填充下拉框
        List<Role> roles = roleService.findAllRoles();
        model.addAttribute("roles", roles);

        // 查询用户信息显示到页面
        User user = userService.getUser(usrId);
        model.addAttribute("user", user);
        return "user/edit";
    }

    /**
     * 执行新增或修改用户信息
     */
    @PostMapping("/save")
    public String save(User user) {
        userService.saveUser(user);
        return "redirect:/user/list";
    }

    /**
     * 根据ID删除用户信息
     */
    @ResponseBody
    @GetMapping("/del/{usrId}")
    public Object del(@PathVariable("usrId") Long usrId) {
        boolean flag = userService.deleteUser(usrId);
        Map map = new HashMap();
        map.put("delResult","true");
        return map;
    }
}
